﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Utilities;
using Billing.Dtos;
using System.Windows.Controls.Primitives;
using Billing.Controls;
using System.Configuration;
using System.Data;

namespace Billing.Windows
{
    /// <summary>
    /// Interaction logic for Stock.xaml
    /// </summary>
    public partial class StockAllBranches : Window
    {
        public string code = string.Empty;
        public string desc = string.Empty;
        public WindowTypes m_windowType;

        public StockAllBranches()
        {
            InitializeComponent();

            try
            {
                foreach (Branch branch in Database.GetBranches())
                {
                    if (branch.BranchID.ToString() != Database.Branch)
                        cmbBranch.Items.Add(new ComboBoxItem { Content = branch.BranchName, Tag = branch.BranchID });
                }

                if (cmbBranch.Items.Count > 0)
                    cmbBranch.SelectedIndex = 0;

                //BindAllItemstoGrid(CacheManager.BillingItems);
                txtCodeSearch.Focus();

                //txtItemQty.Visibility = System.Windows.Visibility.Hidden;
                //lblItemQty.Visibility = System.Windows.Visibility.Hidden;
                //bAddStock.Visibility = System.Windows.Visibility.Hidden;

                SetDefaults();
            }
            catch (Exception) { }
        }

        private void BindAllItemstoGrid(List<BillingGridItemDto> list)
        {
            try
            {
                List<StockItemControlAllBranches> mainList = new List<StockItemControlAllBranches>();
                foreach (BillingGridItemDto item in list)
                {
                    StockItemControlAllBranches stockItem = new StockItemControlAllBranches();
                    stockItem.lblCode.Content = item.Code;
                    stockItem.lblDescription.Content = item.Name;
                    stockItem.lblStock.Content = item.Stock;
                    stockItem.lblPrice.Content = item.Price;
                    mainList.Add(stockItem);
                }

                lbStockGrid.ItemsSource = mainList;
            }
            catch (Exception) { }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
            if (e.Key == Key.Left && txtCodeSearch.IsFocused)
            {
                cmbBranch.Focus();
            }
            else if (e.Key == Key.Right && cmbBranch.Focus())
            {
                //txtCodeSearch.Focus();
                TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
                if (elementWithFocus != null)
                    elementWithFocus.MoveFocus(request);
            }
            else if (e.Key == Key.Down && txtCodeSearch.IsFocused)
            {
                if (lbStockGrid.Items.Count > 1)
                {
                    lbStockGrid.Focus();
                    lbStockGrid.SelectedIndex = 0;
                }
            }
            else if (e.Key == Key.Enter && txtCodeSearch.IsFocused) 
            {
                lbStockGrid.Items.Clear();

                DataTable dtValues = Database.GetOtherBranchItems((cmbBranch.SelectedItem as ComboBoxItem).Tag.ToString(), txtCodeSearch.Text);

                if (CacheManager.BillingItems.Count == 0)
                    CacheManager.LoadItems();

                if (dtValues != null)
                {
                    lbStockGrid.Items.Add(new StockItemControlAllBranches());
                    foreach (DataRow row in dtValues.Rows)
                    {
                        StockItemControlAllBranches item = new StockItemControlAllBranches();
                        item.lblCode.Content = row["ItemCode"].ToString();
                        item.lblDescription.Content = row["ItemName"].ToString();
                        item.lblPrice.Content = row["SellingPrice"].ToString();
                        item.lblStock.Content = row["StockAvailable"].ToString();
                        if (CacheManager.BillingItems.Count > 0 && CacheManager.BillingItems.Exists(localItem => localItem.Code == int.Parse(item.lblCode.Content.ToString())))
                           item.lblStockCurrentBranch.Content = CacheManager.BillingItems.Find(localItem => localItem.Code == int.Parse(item.lblCode.Content.ToString())).Stock;
                        lbStockGrid.Items.Add(item);
                    }
                    //MessageBox.Show((cmbBranch.SelectedItem as ComboBoxItem).Content.ToString() + " Branch Items Populated", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                else
                {
                    lbStockGrid.Items.Clear();
                    //MessageBox.Show("Unable to Fetch Data", "Failed to Fetch", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else if (e.Key == Key.Enter && lbStockGrid.SelectedItems.Count == 1 && (lbStockGrid.SelectedItems[0] as StockItemControlAllBranches).lblCode.Content.ToString() != "Code")
            {
                txtItemQty.Focus();
                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblCode.Foreground = new SolidColorBrush(Colors.Red);
                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblCode.FontWeight = FontWeights.Bold;

                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblDescription.Foreground = new SolidColorBrush(Colors.Red);
                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblDescription.FontWeight = FontWeights.Bold;

                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblPrice.Foreground = new SolidColorBrush(Colors.Red);
                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblPrice.FontWeight = FontWeights.Bold;

                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblStock.Foreground = new SolidColorBrush(Colors.Red);
                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblStock.FontWeight = FontWeights.Bold;

                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblStockCurrentBranch.Foreground = new SolidColorBrush(Colors.Red);
                (lbStockGrid.SelectedItem as StockItemControlAllBranches).lblStockCurrentBranch.FontWeight = FontWeights.Bold;
            }
            else if (e.Key == Key.F1)
            {
                AddStock();
            }
        }

        //private bool ValidateFields()
        //{
        //    try
        //    {
        //        if (txtItemQty.Text.Trim() == string.Empty)
        //        {
        //            txtItemQty.Focus();
        //            return false;
        //        }
        //        else
        //        {
        //            string qty = txtItemQty.Text;
        //            double result;
        //            if (!(double.TryParse(qty, out result)))
        //            {
        //                MessageBox.Show("Please enter valid Item Qty", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        //                txtItemQty.Text = string.Empty;
        //                return false;
        //            }
        //        }
        //        return true;
        //    }
        //    catch (Exception) 
        //    {
        //        return false;
        //    }
        //}

        //void AddStock()
        //{
        //    try
        //    {
        //        BillingGridItemDto selectedItem = (BillingGridItemDto)GetSelectedStockItem((StockItemControl)lbStockGrid.SelectedItem);
        //        int selectedItemCode = selectedItem.Code;

        //        if (ValidateFields())
        //        {
        //            int result = Database.AddStock(selectedItemCode, double.Parse(txtItemQty.Text.Trim()));
        //            if (result != 0)
        //            {
        //                txtItemQty.Clear();
        //                txtCodeSearch.Clear();
        //                txtCodeSearch.Focus();
        //                MessageBox.Show("Stock Added", "Stock", MessageBoxButton.OK);
        //                CacheManager.ResetCacheManager();
        //                this.Close();
        //            }
        //        }
        //    }
        //    catch (Exception) { }
        //}

        BillingGridItemDto GetSelectedStockItem(StockItemControlAllBranches selectedItem)
        {
            try
            {
                BillingGridItemDto item = new BillingGridItemDto();
                item.Code = Convert.ToInt32(selectedItem.lblCode.Content.ToString().Trim());
                item.Qty = Convert.ToDouble(selectedItem.lblStock.Content.ToString().Trim());
                item.Name = selectedItem.lblDescription.Content.ToString().Trim();
                item.Price = Convert.ToDouble(selectedItem.lblPrice.Content.ToString().Trim());
                return item;
            }
            catch (Exception) 
            {
                return null;
            }
        }

        //private void dGAllItems_EnterKey(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        txtItemQty.Focus();
        //    }
        //    catch (Exception) { }
        //}

        List<BillingGridItemDto> SearchResult()
        {
            //TODO: Need to find a way to get stcok items from all the braches for MainMenu
            List<Dtos.BillingGridItemDto> items = Utilities.CacheManager.BillingItems;
            List<Dtos.BillingGridItemDto> results = new List<Dtos.BillingGridItemDto>();
            string pattern = txtCodeSearch.Text.Trim();

            //if (items.Exists(i => i.Code.ToString() == txtCodeSearch.Text.Trim()))
            //{
            //    return items.FindAll(i => i.Code.ToString() == txtCodeSearch.Text.Trim());
            //}
            //else
            //{
            //    return items;
            //}
            foreach (BillingGridItemDto item in items)
                if (System.Text.RegularExpressions.Regex.IsMatch(item.Name.Trim(), pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase) || System.Text.RegularExpressions.Regex.IsMatch(item.Code.ToString().Trim(), pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    results.Add(item);

            return results;
        }

        private void txtCodeSearch_KeyUp(object sender, KeyEventArgs e)
        {
            //if (e.Key == Key.F1)
            //{
            //    lbStockGrid.Items.Clear();

            //    DataTable dtValues = Database.GetOtherBranchItems((cmbBranch.SelectedItem as ComboBoxItem).Tag.ToString(), txtCodeSearch.Text);

            //    if (dtValues != null)
            //    {
            //        foreach (DataRow row in dtValues.Rows)
            //        {
            //            StockItemControl item = new StockItemControl();
            //            item.lblCode.Content = row["ItemCode"].ToString();
            //            item.lblDescription.Content = row["ItemName"].ToString();
            //            item.lblPrice.Content = row["SellingPrice"].ToString();
            //            item.lblStock.Content = row["StockAvailable"].ToString();
            //            lbStockGrid.Items.Add(item);
            //        }
            //    }
            //    else
            //    {
            //        lbStockGrid.Items.Clear();
            //        MessageBox.Show("Unable to Fetch Data", "Failed to Fetch", MessageBoxButton.OK, MessageBoxImage.Warning);
            //    }
            //}
        }

        public void SetDefaults()
        {
            switch (m_windowType)
            {
                case WindowTypes.MainWindowF8:
                    {
                        lbAddStock.Text = "Stock Search(All Branch)";
                        break;
                    }
                case WindowTypes.BillingWindowF1:
                    {
                        lbAddStock.Text = "Help";
                        break;
                    }
                case WindowTypes.BillingWindowF8:
                    {
                        lbAddStock.Text = "Stock Search";
                        break;
                    }
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void cmbBranch_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Right || e.Key == Key.Left)
                e.Handled = true;
            else
                e.Handled = false;
        }

        private bool ValidateFields(BillingGridItemDto item)
        {
            try
            {
                double result;
                DataTable dtValues = null;

                if (txtItemQty.Text.Trim() == string.Empty)
                {
                    txtItemQty.Focus();
                    return false;
                }
                else
                {
                    dtValues = Database.GetItem(item.Code.ToString());

                    string qty = txtItemQty.Text;
                    if ((bool)(dtValues.Rows[0]["AcceptDecimalStock"]))
                    {
                        if (!(double.TryParse(qty, out result)))
                        {
                            MessageBox.Show("Please enter valid Item Qty", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            txtItemQty.Text = string.Empty;
                            return false;
                        }
                    }
                    else
                    {
                        int res;
                        if (!(int.TryParse(qty, out res)))
                        {
                            MessageBox.Show("Please enter valid Item Qty", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            txtItemQty.Text = string.Empty;
                            return false;
                        }
                        result = res;
                    }
                }

                //Check Available Qty
                if (Convert.ToDouble(dtValues.Rows[0]["StockAvailable"]) < result)
                {
                    MessageBox.Show("Enter Qty exceeds Available Stock", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    txtItemQty.Text = string.Empty;
                    txtItemQty.Focus();
                    return false;
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        void AddStock()
        {
            try
            {
                BillingGridItemDto selectedItem = (BillingGridItemDto)GetSelectedStockItem((StockItemControlAllBranches)lbStockGrid.SelectedItem);
                int selectedItemCode = selectedItem.Code;

                if (ValidateFields(selectedItem))
                {
                    if (MessageBoxResult.OK == MessageBox.Show("Do you want to Transfer the Stock to " + cmbBranch.SelectionBoxItem.ToString() + " Branch", "Stock Transfer Confirmation", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                    {
                        int result = Database.AddStockToBranch(selectedItemCode, double.Parse(txtItemQty.Text.Trim()), (cmbBranch.SelectedItem as ComboBoxItem).Tag.ToString());
                        if (result > 0)
                        {
                            txtItemQty.Clear();
                            txtCodeSearch.Clear();
                            txtCodeSearch.Focus();
                            MessageBox.Show("Stock Transferred Successfully                        ", "Stock Transferred", MessageBoxButton.OK);
                            CacheManager.ResetCacheManager();
                            lbStockGrid.ItemsSource = null;

                            lbStockGrid.Items.Clear();

                            DataTable dtValues = Database.GetOtherBranchItems((cmbBranch.SelectedItem as ComboBoxItem).Tag.ToString(), txtCodeSearch.Text);

                            if (dtValues != null)
                            {
                                lbStockGrid.Items.Add(new StockItemControlAllBranches());
                                foreach (DataRow row in dtValues.Rows)
                                {
                                    StockItemControlAllBranches item = new StockItemControlAllBranches();
                                    item.lblCode.Content = row["ItemCode"].ToString();
                                    item.lblDescription.Content = row["ItemName"].ToString();
                                    item.lblPrice.Content = row["SellingPrice"].ToString();
                                    item.lblStock.Content = row["StockAvailable"].ToString();
                                    if (CacheManager.BillingItems.Count > 0 && CacheManager.BillingItems.Exists(localItem => localItem.Code == int.Parse(item.lblCode.Content.ToString())))
                                        item.lblStockCurrentBranch.Content = CacheManager.BillingItems.Find(localItem => localItem.Code == int.Parse(item.lblCode.Content.ToString())).Stock;
                                    lbStockGrid.Items.Add(item);
                                }
                            }

                            //BindAllItemstoGrid(CacheManager.BillingItems);
                            //this.Close();
                        }
                        else
                        {
                            MessageBox.Show("Some Unknown Error Has Occurred", "Some Error", MessageBoxButton.OK);
                        }
                    }
                }
            }
            catch (Exception) { }
        }
    }
}
